package com.example.sinoyd.frameapplication.KotlinFrame.MpChart

import android.content.Context
import android.graphics.Color
import com.example.sinoyd.frameapplication.KotlinFrame.Dataclass.Chartdata
import com.github.mikephil.charting.charts.CombinedChart
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.*
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet
import org.jetbrains.anko.runOnUiThread
import java.util.*
import java.util.logging.Handler
import kotlin.collections.ArrayList
import kotlin.collections.HashMap

/**
 * 作者： scj
 * 创建时间： 2018/5/21
 * 版权： 江苏远大信息股份有限公司
 * 描述： 实现【单个柱状图】【单个折线图】【2个柱状图叠加】【多个折线图】
 *
 * 组合图
 */

class CombinedChartDrawing {

    var combinedChart: CombinedChart
    var newlist: HashMap<String, ArrayList<Chartdata>> = HashMap()
    var type: String
    var modify_Y_axis: Boolean
    var Randomcolor: Boolean
    // 颜色数据
    private var colorgroup: MutableList<Int>
    var DrawValues: Boolean
    var legendable: Boolean
    var cont: Context

    constructor(con: Context,
                combinedChart: CombinedChart,//控件
                list: HashMap<String, ArrayList<Chartdata>>,//数据源
                type: String,//图标类型
                modify_Y_axis: Boolean,//是否修改Y轴
                Randomcolor: Boolean,//是否用随机颜色还是标准颜色
                DrawValues: Boolean,//数据是否显示
                legendable: Boolean//图列是否显示
    ) {
        this.cont = con
        this.legendable = legendable
        this.DrawValues = DrawValues
        this.combinedChart = combinedChart
        this.type = type
        this.newlist = list
        this.modify_Y_axis = modify_Y_axis
        this.colorgroup = ArrayList()
        this.Randomcolor = Randomcolor
        if (Randomcolor) {
            //随机颜色
            for (i in 0 until list.size) {
                colorgroup.add(generateRandomColor())
            }
        } else {
            //标准颜色
            colorgroup = arrayListOf(
                    Color.rgb(78, 255, 255),//一级
                    Color.rgb(78, 255, 255),//二级
                    Color.rgb(75, 255, 0),//三级
                    Color.rgb(255, 255, 0),//四级
                    Color.rgb(246, 122, 19),//五级
                    Color.rgb(243, 1, 21)//六级
            )
        }


    }


    //随机颜色RGB
    private fun generateRandomColor(): Int {
        val random = Random()
        val red = random.nextInt(256)
        val green = random.nextInt(256)
        val blue = random.nextInt(256)
        return Color.rgb(red, green, blue)
    }

    companion object {
        var ONLY_BROKEN_LINE: String = "单折线图"
        var MORE_BROKEN_LINE: String = "多折线图"
        var ONLY_BAR_GRAPH: String = "单柱状图"
        var MORE_BAR_GRAPH_TRANSVERSE: String = "多柱状图横向"
        var MORE_BAR_GRAPH_PORTRAIT: String = "多柱状图纵向"
    }

    fun initview(): CombinedChartDrawing {


        combinedChart.setDrawBorders(false) // 显示边界,四周都有外框
        combinedChart.description.isEnabled = false// 不显示备注信息
//        combinedChart.setBackgroundColor(Color.WHITE)//设置背景颜色
        combinedChart.setDrawGridBackground(false)//底部灰色颜色
        combinedChart.setDrawBarShadow(false)//绘制当前展示的内容顶部阴影
        combinedChart.isHighlightFullBarEnabled = false //渐变
        combinedChart.setPinchZoom(true) // 比例缩放上下左右缩放
        combinedChart.animateY(1500)//动画时长

        //设置透明
//        combinedChart.alpha = 0.8f


        //设置chart是否可以触摸
        combinedChart.setTouchEnabled(true)
        //设置是否可以拖拽
        combinedChart.isDragEnabled = true
        //设置是否可以缩放 x和y，默认true
        combinedChart.setScaleEnabled(false)
        //是否缩放X轴
        combinedChart.isScaleXEnabled = false
//        //X轴缩放比例
//        combinedChart.scaleX = 1.5f
//        //Y轴缩放比例
//        combinedChart.scaleY = 1.5f
        //是否缩放Y轴
        combinedChart.isScaleYEnabled = false
        //设置是否可以通过双击屏幕放大图表。默认是true
        combinedChart.isDoubleTapToZoomEnabled = false

        // draw bars behind lines
        combinedChart.drawOrder = arrayOf(CombinedChart.DrawOrder.BAR, CombinedChart.DrawOrder.BUBBLE, CombinedChart.DrawOrder.CANDLE, CombinedChart.DrawOrder.LINE, CombinedChart.DrawOrder.SCATTER)


        //图例是否显示
        val l = combinedChart.legend
        l.isEnabled = legendable  //是否显示图例
        l.isWordWrapEnabled = true
        l.verticalAlignment = Legend.LegendVerticalAlignment.BOTTOM
//        l.horizontalAlignment = Legend.LegendHorizontalAlignment.CENTER
        l.orientation = Legend.LegendOrientation.HORIZONTAL
        l.setDrawInside(false)


        //右边的y轴
        val rightAxis = combinedChart.axisRight
        rightAxis.setDrawGridLines(false)//y轴的网格线
        rightAxis.axisMinimum = 0f // 最小刻度
        rightAxis.isEnabled = false//是否显示


        //左边的y轴
        val leftAxis = combinedChart.axisLeft
        leftAxis.granularity = 1f//每一个刻度占多少
        leftAxis.setDrawGridLines(false)//y轴的网格线
        leftAxis.axisMinimum = 0f //最小刻度
//        leftAxis.valueFormatter = IAxisValueFormatter { value, axis -> (value.toInt() + 5).toString() + "" }//显示字体格式
        leftAxis.textColor = Color.BLACK//显示字体颜色
        //重写Y轴上的显示
        if (modify_Y_axis) {
            combinedChart.rendererLeftYAxis = WQIYAxisRendererCombinedChart(combinedChart)
            leftAxis.setValueFormatter { value, axis ->
                when (value) {
                    0.0f -> "I"
                    1.0f -> "II"
                    2.0f -> "III"
                    3.0f -> "IV"
                    4.0f -> "V"
                    5.0f -> "劣V"
                    else -> ""
                }
            }
        }
        leftAxis.textSize = 5f

        //x轴的数据
        val xAxis = combinedChart.xAxis
        xAxis.position = XAxis.XAxisPosition.BOTTOM//显示位置
        xAxis.axisMinimum = -0.5f//最小刻度
        xAxis.granularity = 1f//每一个刻度占多少
        xAxis.setDrawGridLines(false)//x轴的网格线
        xAxis.labelRotationAngle = -20f//设置x轴字体显示角度
        xAxis.valueFormatter = IAxisValueFormatter { value, axis ->
            try {
                newlist[newlist.keys.first()]!![value.toInt()].time
            } catch (e: Exception) {
                ""
            }
        }
        xAxis.textColor = Color.BLACK
        xAxis.textSize = 5f
        return this

    }


    fun showchart() {
        var data = CombinedData()
        when (type) {
        //加装2个叠在一起的柱状图数据
            MORE_BAR_GRAPH_PORTRAIT -> {
                data.setData(generateBarData2(newlist.keys.first(), newlist[newlist.keys.first()]!!))
            }
        //单条折线图
            ONLY_BROKEN_LINE -> {
                data.setData(generateLineData(newlist.keys.first(), newlist[newlist.keys.first()]!!))
            }
        //单个柱状图
            ONLY_BAR_GRAPH -> {
                data.setData(generateBarData1(newlist.keys.first(), newlist[newlist.keys.first()]!!))
            }
        //多条折线
            MORE_BROKEN_LINE -> {
                data.setData(generateLineDataMore(newlist))
            }
        }




        combinedChart.xAxis.axisMaximum = data.xMax + 0.35f//解决最后一个柱状图显示不全的问题
        combinedChart.data = data//给入数据
        combinedChart.setVisibleXRangeMaximum(7f)//需要在设置数据源后生效 一个界面最多多少个数据。
        combinedChart.setVisibleXRangeMinimum(7f)//设置最少数量，不常用。
        combinedChart.setNoDataText("无数据")//当没有数据时候的显示文字描述
        combinedChart.invalidate()//画图

    }


    //加装折线图数据
    private fun generateLineData(name: String, listvalue: ArrayList<Chartdata>): LineData {
        val d = LineData()
        val entries = java.util.ArrayList<Entry>()
        var colors: ArrayList<Int> = ArrayList()
        for ((index, item) in listvalue.withIndex()) {
            try {
                //取颜色
                when (item.values.toFloat()) {
                    0f -> {
                        colors.add(colorgroup[0])
                    }
                    1f -> {
                        colors.add(colorgroup[1])
                    }
                    2f -> {
                        colors.add(colorgroup[1])
                    }
                    3f -> {
                        colors.add(colorgroup[2])
                    }
                    4f -> {
                        colors.add(colorgroup[3])
                    }
                    5f -> {
                        colors.add(colorgroup[4])
                    }
                    6f -> {
                        colors.add(colorgroup[5])
                    }
                    else -> {
                        colors.add(Color.rgb(0, 0, 0))
                    }
                }
                entries.add(Entry(index + 0.0f, item.values.toFloat()))

            } catch (e: Exception) {
                entries.add(Entry(index + 0.0f, 0.toFloat()))
            }
        }

        val set = LineDataSet(entries, name)
        set.color = Color.rgb(0, 0, 0)//直线颜色
        set.lineWidth = 2.5f//直线宽度【细  粗】
        set.circleColors = colors
        set.circleRadius = 5f//弧度
        set.setCircleColorHole(Color.rgb(255, 255, 255))//填充色
        set.mode = LineDataSet.Mode.LINEAR
        set.setDrawValues(DrawValues)
        set.valueTextSize = 10f//字体大小
        set.valueTextColor = Color.rgb(0, 0, 255)//字体颜色
        set.axisDependency = YAxis.AxisDependency.LEFT
        d.addDataSet(set)
        return d
    }

    //加装多条折线图数据
    private fun generateLineDataMore(list: HashMap<String, ArrayList<Chartdata>>): LineData {
        var lineData: MutableList<ILineDataSet> = ArrayList()

        for ((n, item) in list.keys.withIndex()) {
            var yVals = ArrayList<Entry>()
            for ((index, it) in list[item]!!.withIndex()) {
                try {
                    yVals.add(Entry(index.toFloat(), it.values.toFloat()))
                } catch (e: Exception) {
                    yVals.add(Entry(index.toFloat(), 0.toFloat()))
                }
            }
            var set = LineDataSet(yVals, item)
            set.color = colorgroup[n]
            set.setCircleColor(colorgroup[n])
            set.circleHoleRadius = 2f
            set.circleRadius = 4f
            set.valueTextColor = colorgroup[n]
            set.setDrawValues(DrawValues)
            lineData.add(set)
        }
        return LineData(lineData)
    }

    //加装2个叠在一起的柱状图数据
    private fun generateBarData2(name: String, listvalue: ArrayList<Chartdata>): BarData {

        val entries2 = ArrayList<BarEntry>()
        var colors: ArrayList<Int> = ArrayList()
        for ((index, item) in listvalue.withIndex()) {
            try {
                //取颜色
                when (item.values.toFloat()) {
                    0f -> {
                        colors.add(Color.parseColor("#dcdcdc"))
                        colors.add(colorgroup[0])
                    }
                    1f -> {
                        colors.add(Color.parseColor("#dcdcdc"))
                        colors.add(colorgroup[1])
                    }
                    2f -> {
                        colors.add(Color.parseColor("#dcdcdc"))
                        colors.add(colorgroup[1])
                    }
                    3f -> {
                        colors.add(Color.parseColor("#dcdcdc"))
                        colors.add(colorgroup[2])
                    }
                    4f -> {
                        colors.add(Color.parseColor("#dcdcdc"))
                        colors.add(colorgroup[3])
                    }
                    5f -> {
                        colors.add(Color.parseColor("#dcdcdc"))
                        colors.add(colorgroup[4])
                    }
                    6f -> {
                        colors.add(Color.parseColor("#dcdcdc"))
                        colors.add(colorgroup[5])
                    }
                    else -> {
                        colors.add(Color.parseColor("#dcdcdc"))
                        colors.add(Color.rgb(0, 0, 0))
                    }
                }
                if (item.values.toFloat() == 0.0f) {
                    entries2.add(BarEntry(index + 0.0f, floatArrayOf(0f, 0f)))
                } else {
                    entries2.add(BarEntry(index + 0.0f, floatArrayOf(item.values.toFloat() - 0.2f, 0.2f)))
                }

            } catch (e: Exception) {
                entries2.add(BarEntry(index + 0.0f, floatArrayOf(0f, 0f)))
            }
        }

        val set2 = BarDataSet(entries2, name)
        set2.stackLabels = arrayOf("", "")//图列显示内容
        set2.colors = colors
        set2.valueTextColor = Color.rgb(0, 0, 0)
        set2.valueTextSize = 10f
        set2.axisDependency = YAxis.AxisDependency.LEFT
        set2.setDrawValues(DrawValues)
        set2.setValueFormatter { value, entry, dataSetIndex, viewPortHandler ->
            if (value.toString() == "0.2") {
                entry.y.toString()
            } else {
                ""
            }
        }
        val barWidth = 0.45f // x2 dataset
        val d = BarData(set2)
        d.barWidth = barWidth

        return d
    }

    //加装一个柱状图
    private fun generateBarData1(name: String, listvalue: ArrayList<Chartdata>): BarData {

        val entries1 = ArrayList<BarEntry>()

        for ((index, item) in listvalue.withIndex()) {
            try {
                entries1.add(BarEntry(index + 0.0f, item.values.toFloat()))
            } catch (e: Exception) {
                entries1.add(BarEntry(index + 0.0f, 0.toFloat()))
            }
        }

        val set1 = BarDataSet(entries1, name)
        set1.color = Color.rgb(60, 220, 78)
        set1.valueTextColor = Color.rgb(0, 0, 0)
        set1.valueTextSize = 10f
        set1.axisDependency = YAxis.AxisDependency.LEFT
        set1.setDrawValues(DrawValues)
        val barWidth = 0.45f // x2 dataset
        val d = BarData(set1)
        d.barWidth = barWidth
        return d
    }

}